package com.calvin.study.threadsafe.lock.viewlock;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;

import com.calvin.study.utils.IncrementData;
import com.calvin.study.utils.Print;

public class CLHLockTest {

	public static void main(String[] args) {
		testCLHLock();
	}

	public static int sum = 0;

	public static void testCLHLock() {
		// 速度对比
		// ReentrantLock 1 000 000 次 0.154 秒
		// CLHLock 1 000 000 次 2.798 秒

		// 每个线程的执行轮数
		final int TURNS = 100000;
		// 线程数
		final int THREADS = 10;
		// 线程池， 用于多线程模拟测试
		ExecutorService pool = Executors.newFixedThreadPool(THREADS);
		Lock lock = new CLHLock();
		//Lock lock = new ReentrantLock();
		// 倒数闩
		CountDownLatch countDownLatch = new CountDownLatch(THREADS);
		long start = System.currentTimeMillis();

		// 启用10个线程
		for (int i = 0; i < THREADS; i++) {
			pool.submit(() -> {
				//这里并非每个线程执行1000000次，临界区代码是sum。
				for (int j = 0; j < TURNS; j++) {
					IncrementData.lockAndFastIncrease(lock);
				}
				Print.tcfo("本线程累加完成，sum: " );
				// 倒数闩减少1次
				countDownLatch.countDown();
			});
		}
		try {
			// 等待倒数闩归0， 所有线程结束
			countDownLatch.await();
		} catch (Exception e) {
			e.printStackTrace();
		}
		float time = (System.currentTimeMillis() - start) / 1000F;

		// 输出统计结果
		Print.tcfo("运行的时长为： " + time);
		Print.tcfo("累加结果为： " + IncrementData.sum);
	}

}
